package fire;
/**
 * Friendly Interactive Recursion Educator (FIRE)
 * COMS 4115: Programming Languages & Translators
 * Prof. Aho
 * 
 * @author Brian Lu
 * @author Sahar Hasan
 * @author Steve Hehl
 * @author Tristan Naumann
 * @version 2009-05-12
 */
import org.antlr.runtime.*;
import org.antlr.stringtemplate.*;
import java.io.*;
import java.util.*;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class CompilerMain {
	
	public static StringTemplateGroup templates;
	public static String[] copyfiles = {
		"Fire.java", "Node.java", "Tree.java", "Fire.stg"
	};
	
	public static void main(String[] args) throws Exception {
		// Output files to fire folder
		for (String f : copyfiles) {
			(new File("fire")).mkdir();
			FileWriter outf = new FileWriter("fire/"+f);
			Scanner s = new Scanner(CompilerMain.class.getResourceAsStream(f));
			while (s.hasNext())  outf.write(s.nextLine() + "\n");
			s.close();
			outf.close();
		}
		
		//Read in Fire/Java copied template file Fire.stg
    	FileReader groupfile = new FileReader("fire/Fire.stg");
    	StringTemplateGroup templates = new StringTemplateGroup(groupfile);
    	groupfile.close();
    	
    	//Kill string template group file after use
    	File kill = new File("fire/Fire.stg");
    	kill.delete();
    	
    	//Get user input file x.fire
    	JFrame frame = new JFrame("Fire GUI--Select a FIRE source file");
    	JFileChooser fc = new JFileChooser();
    	fc.showOpenDialog(frame);
    	File selFile = fc.getSelectedFile();
    	frame.dispose();
    	
    	//String file = new String("code/firegrammar/input");
    	ANTLRFileStream input = new ANTLRFileStream(selFile.toString()); 
     
    	FireLexer lexer = new FireLexer(input);
    	WSFilter filter = new WSFilter(lexer);
        CommonTokenStream tokens = new CommonTokenStream(filter);
        FireParser parser = new FireParser(tokens);
        parser.setTemplateLib(templates);
        FireParser.s_return r = parser.s();
        StringTemplate program = (StringTemplate) r.getTemplate();
     //   System.out.println(program.toString());

        
        //    WRITE JavaHelper.java TO FILE
        FileWriter fstream = new FileWriter(new File("fire/FireHelper.java"));
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(program.toString());
        out.close();
        
        // try to compile and run
        System.out.println("Compiling generated Java files.");
        Process p = Runtime.getRuntime().exec("javac fire/*.java");
        p.waitFor();
  
        System.out.println("Trying to run, to run manually type \"java fire.Fire\".");
        Runtime.getRuntime().exec("java fire.Fire");
        
        //System.out.println("DONE");
	} 
}
